const path = require("path");
const fs = require("fs-extra");
const inquirer = require("inquirer");
const Generator = require("./generator");

const create = async (name, option) => {
  console.log("create");
  // 当前命令行选择的目录
  const cwd = process.cwd();
  // 需要创建的目录地址
  const targetDir = path.join(cwd, name);

  // 判断目录是否已经存在
  if (fs.existsSync(targetDir)) {
    // 目录已经存在
    if (option.force) {
      // 强制创建
      await fs.remove(targetDir);
    } else {
      // 询问用户是否确定要覆盖
      const { action } = await inquirer.prompt([
        {
          name: "action",
          type: "list",
          message: "文件夹已经存在，请选择如下操作：",
          choices: [
            {
              name: "Overwrite",
              value: "overwrite",
            },
            {
              name: "Cancel",
              value: false,
            },
          ],
        },
      ]);

      if (action === "overwrite") {
        await fs.remove(targetDir);
      } else {
        return;
      }
    }
  }

  // 创建项目
  const generator = new Generator(name, targetDir);
  generator.create();
};

module.exports = {
  create,
};
